package com.zcxx.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * 文件存储工具类
 * 用于处理文件上传和删除操作
 */
@Component
@Slf4j
public class FileStorageUtil {

    /**
     * 文件上传目录
     */
    @Value("${file.upload-dir}")
    private String uploadDir;

    /**
     * 存储上传的文件
     *
     * @param file 上传的文件对象
     * @return 存储的文件名
     * @throws IOException 如果文件读写过程中发生错误
     */
    public String storeFile(MultipartFile file) throws IOException {
        try {
            // 获取上传目录的路径
            Path uploadPath = Paths.get(uploadDir);
            // 检查上传目录是否存在，如果不存在则创建
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一的文件名，避免文件名冲突
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            // 获取文件的完整路径
            Path filePath = uploadPath.resolve(fileName);
            // 将上传的文件内容复制到指定路径
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 记录日志信息，确认文件已存储
            log.info("File stored: {}", filePath);
            return fileName;
        } catch (IOException e) {
            log.error("Failed to store file: {}", file.getOriginalFilename(), e);
            throw new IOException("Failed to store file: " + file.getOriginalFilename(), e);
        }
    }

    /**
     * 删除指定文件名的文件
     *
     * @param fileName 要删除的文件名
     * @throws IOException 如果文件删除过程中发生错误
     */
    public void deleteFile(String fileName) throws IOException {
        try {
            // 根据文件名和上传目录构建文件路径
            Path filePath = Paths.get(uploadDir, fileName);
            File file = filePath.toFile();
            // 检查文件是否存在
            if (file.exists()) {
                // 尝试删除文件，并确认是否删除成功
                if (file.delete()) {
                    log.info("File deleted successfully: {}", filePath);
                } else {
                    // 如果删除失败，记录错误信息并抛出异常
                    log.error("Failed to delete file: {}", filePath);
                    throw new IOException("Failed to delete file: " + filePath);
                }
            } else {
                // 如果文件不存在，记录警告信息
                log.warn("File does not exist: {}", filePath);
            }
        } catch (IOException e) {
            log.error("Failed to delete file: {}", fileName, e);
            throw new IOException("Failed to delete file: " + fileName, e);
        }
    }
}
